package com.example.crm.controller.api;

import com.example.crm.vo.Result;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 仪表板API控制器
 * 提供首页和各类业务统计数据
 */
@RestController
@RequestMapping("/api/dashboard")
public class DashboardAPIController {

    /**
     * 获取主仪表板统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getDashboardStats() {
        // 模拟数据
        Map<String, Object> data = new HashMap<>();
        
        // 关键指标
        Map<String, Object> keyMetrics = new HashMap<>();
        keyMetrics.put("totalCustomers", 1245);
        keyMetrics.put("activeCustomers", 876);
        keyMetrics.put("totalSales", 2460000);
        keyMetrics.put("openDeals", 47);
        keyMetrics.put("avgDealValue", 52340.42);
        keyMetrics.put("customerSatisfaction", 4.7);
        keyMetrics.put("openServiceTickets", 34);
        data.put("keyMetrics", keyMetrics);
        
        // 趋势数据
        List<Map<String, Object>> trend = new ArrayList<>();
        String[] months = {"一月", "二月", "三月", "四月", "五月", "六月"};
        Random random = new Random();
        double lastSales = 350000;
        double lastCustomers = 1100;
        
        for (String month : months) {
            Map<String, Object> item = new HashMap<>();
            item.put("period", month);
            
            // 销售额有一定的连续性变化
            lastSales = lastSales * (0.9 + random.nextDouble() * 0.2);
            item.put("sales", Math.round(lastSales));
            
            // 客户数有一定的连续性变化
            lastCustomers = lastCustomers * (0.95 + random.nextDouble() * 0.1);
            item.put("customers", Math.round(lastCustomers));
            
            item.put("deals", 30 + random.nextInt(25));
            item.put("tickets", 20 + random.nextInt(30));
            trend.add(item);
        }
        data.put("trend", trend);
        
        // 最近活动
        List<Map<String, Object>> recentActivities = new ArrayList<>();
        String[] activities = {
            "新客户注册: 华为技术有限公司",
            "成功签约: 腾讯科技 - ¥320,000",
            "服务工单完成: 阿里巴巴集团 #45623",
            "新销售机会: 小米科技 - ¥150,000预估",
            "客户回访: 百度在线网络技术有限公司",
            "合同更新: 京东科技 - ¥280,000/年",
            "投诉解决: 网易公司 #32145"
        };
        
        int[] times = {5, 12, 45, 120, 180, 240, 300};
        
        for (int i = 0; i < activities.length; i++) {
            Map<String, Object> activity = new HashMap<>();
            activity.put("id", i + 1);
            activity.put("content", activities[i]);
            activity.put("time", times[i] + " 分钟前");
            activity.put("type", i % 3 == 0 ? "customer" : (i % 3 == 1 ? "sales" : "service"));
            recentActivities.add(activity);
        }
        data.put("recentActivities", recentActivities);
        
        // 销售漏斗
        List<Map<String, Object>> salesFunnel = new ArrayList<>();
        String[] stages = {"线索", "合格", "方案", "谈判", "成交"};
        int[] counts = {200, 120, 80, 50, 30};
        double[] values = {4000000, 2500000, 1800000, 1200000, 750000};
        
        for (int i = 0; i < stages.length; i++) {
            Map<String, Object> stage = new HashMap<>();
            stage.put("stage", stages[i]);
            stage.put("count", counts[i]);
            stage.put("value", values[i]);
            stage.put("conversionRate", i == 0 ? 1.0 : (double)counts[i] / counts[i-1]);
            salesFunnel.add(stage);
        }
        data.put("salesFunnel", salesFunnel);
        
        return Result.success(data);
    }
    
    /**
     * 获取客户相关仪表板数据
     */
    @GetMapping("/customer")
    public Result<Map<String, Object>> getCustomerDashboard() {
        Map<String, Object> data = new HashMap<>();
        
        // 客户统计
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", 1245);
        stats.put("active", 876);
        stats.put("newThisMonth", 42);
        stats.put("churnRate", 0.03);
        stats.put("retentionRate", 0.97);
        stats.put("avgLifetime", 28); // 月
        data.put("stats", stats);
        
        // 客户分布
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("潜在客户", 340);
        distribution.put("新客户", 220);
        distribution.put("活跃客户", 435);
        distribution.put("忠诚客户", 175);
        distribution.put("流失风险", 75);
        data.put("distribution", distribution);
        
        // 客户满意度趋势
        List<Map<String, Object>> satisfaction = new ArrayList<>();
        String[] months = {"一月", "二月", "三月", "四月", "五月", "六月"};
        double[] scores = {4.3, 4.4, 4.2, 4.5, 4.6, 4.7};
        
        for (int i = 0; i < months.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("period", months[i]);
            item.put("score", scores[i]);
            item.put("responses", 80 + new Random().nextInt(50));
            satisfaction.add(item);
        }
        data.put("satisfaction", satisfaction);
        
        // 热门客户
        List<Map<String, Object>> topCustomers = new ArrayList<>();
        String[] companies = {
            "阿里巴巴集团", "腾讯科技", "华为技术", "京东科技", "百度在线"
        };
        double[] values = {580000, 490000, 420000, 380000, 320000};
        
        for (int i = 0; i < companies.length; i++) {
            Map<String, Object> customer = new HashMap<>();
            customer.put("id", i + 1);
            customer.put("name", companies[i]);
            customer.put("value", values[i]);
            customer.put("deals", 5 + new Random().nextInt(8));
            customer.put("satisfaction", 4.0 + new Random().nextDouble());
            topCustomers.add(customer);
        }
        data.put("topCustomers", topCustomers);
        
        return Result.success(data);
    }
    
    /**
     * 获取销售相关仪表板数据
     */
    @GetMapping("/sales")
    public Result<Map<String, Object>> getSalesDashboard() {
        Map<String, Object> data = new HashMap<>();
        
        // 销售统计
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalRevenue", 2460000);
        stats.put("targetRevenue", 3000000);
        stats.put("completionRate", 0.82);
        stats.put("avgDealSize", 52340.42);
        stats.put("avgSalesCycle", 28); // 天
        stats.put("winRate", 0.35);
        data.put("stats", stats);
        
        // 销售趋势
        List<Map<String, Object>> trend = new ArrayList<>();
        String[] months = {"一月", "二月", "三月", "四月", "五月", "六月"};
        double[] revenues = {320000, 380000, 410000, 375000, 450000, 525000};
        int[] deals = {18, 22, 25, 21, 28, 32};
        
        for (int i = 0; i < months.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("period", months[i]);
            item.put("revenue", revenues[i]);
            item.put("deals", deals[i]);
            item.put("target", 400000 + (i * 20000));
            trend.add(item);
        }
        data.put("trend", trend);
        
        // 团队绩效
        List<Map<String, Object>> teamPerformance = new ArrayList<>();
        String[] teams = {"团队A", "团队B", "团队C", "团队D"};
        double[] performances = {0.92, 0.85, 0.75, 0.88};
        double[] quotas = {800000, 700000, 600000, 750000};
        double[] actuals = {736000, 595000, 450000, 660000};
        
        for (int i = 0; i < teams.length; i++) {
            Map<String, Object> team = new HashMap<>();
            team.put("name", teams[i]);
            team.put("performance", performances[i]);
            team.put("quota", quotas[i]);
            team.put("actual", actuals[i]);
            team.put("deals", 15 + new Random().nextInt(20));
            teamPerformance.add(team);
        }
        data.put("teamPerformance", teamPerformance);
        
        // 热门产品
        List<Map<String, Object>> topProducts = new ArrayList<>();
        String[] products = {
            "企业版CRM", "云存储解决方案", "数据分析平台", "安全管理套件", "客户支持系统"
        };
        int[] units = {48, 36, 42, 29, 33};
        double[] productRevenues = {480000, 360000, 294000, 203000, 231000};
        
        for (int i = 0; i < products.length; i++) {
            Map<String, Object> product = new HashMap<>();
            product.put("name", products[i]);
            product.put("units", units[i]);
            product.put("revenue", productRevenues[i]);
            product.put("growth", 0.1 + new Random().nextDouble() * 0.3);
            topProducts.add(product);
        }
        data.put("topProducts", topProducts);
        
        return Result.success(data);
    }
    
    /**
     * 获取服务相关仪表板数据
     */
    @GetMapping("/service")
    public Result<Map<String, Object>> getServiceDashboard() {
        Map<String, Object> data = new HashMap<>();
        
        // 服务统计
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalTickets", 820);
        stats.put("openTickets", 34);
        stats.put("resolvedThisMonth", 142);
        stats.put("avgResponseTime", 4.2); // 小时
        stats.put("avgResolutionTime", 18.5); // 小时
        stats.put("firstContactResolution", 0.68); // 比率
        data.put("stats", stats);
        
        // 服务趋势
        List<Map<String, Object>> trend = new ArrayList<>();
        String[] weeks = {"第1周", "第2周", "第3周", "第4周"};
        int[] newTickets = {45, 38, 42, 39};
        int[] resolvedTickets = {42, 40, 37, 44};
        double[] satisfaction = {4.5, 4.6, 4.4, 4.7};
        
        for (int i = 0; i < weeks.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("period", weeks[i]);
            item.put("new", newTickets[i]);
            item.put("resolved", resolvedTickets[i]);
            item.put("backlog", i == 0 ? 30 : (30 + newTickets[i-1] - resolvedTickets[i-1]));
            item.put("satisfaction", satisfaction[i]);
            trend.add(item);
        }
        data.put("trend", trend);
        
        // 问题分类
        Map<String, Integer> categories = new HashMap<>();
        categories.put("技术问题", 320);
        categories.put("账户问题", 184);
        categories.put("账单问题", 95);
        categories.put("产品咨询", 150);
        categories.put("其他", 71);
        data.put("categories", categories);
        
        // 服务人员绩效
        List<Map<String, Object>> agentPerformance = new ArrayList<>();
        String[] agents = {"张三", "李四", "王五", "赵六", "钱七"};
        int[] tickets = {68, 52, 74, 63, 59};
        double[] times = {3.8, 4.2, 3.5, 4.7, 4.0}; // 小时
        double[] ratings = {4.8, 4.5, 4.6, 4.3, 4.7}; // 5分制
        
        for (int i = 0; i < agents.length; i++) {
            Map<String, Object> agent = new HashMap<>();
            agent.put("name", agents[i]);
            agent.put("ticketsResolved", tickets[i]);
            agent.put("avgResolutionTime", times[i]);
            agent.put("customerRating", ratings[i]);
            agent.put("fcr", 0.5 + new Random().nextDouble() * 0.4); // 首次解决率
            agentPerformance.add(agent);
        }
        data.put("agentPerformance", agentPerformance);
        
        return Result.success(data);
    }
    
    /**
     * 获取活动日历数据
     */
    @GetMapping("/calendar")
    public Result<List<Map<String, Object>>> getCalendarEvents(
            @RequestParam(required = false) String month) {
        
        // 返回模拟的日历事件数据
        List<Map<String, Object>> events = new ArrayList<>();
        Random random = new Random();
        
        // 模拟活动类型
        String[] eventTypes = {
            "会议", "任务截止", "跟进提醒", "客户拜访", "团队活动", "培训"
        };
        
        // 模拟活动内容
        String[][] eventContents = {
            {"销售策略会议", "产品讨论会", "季度回顾", "团队周会", "管理层会议"},
            {"客户方案提交", "合同准备", "报告完成", "预算审批", "项目结项"},
            {"联系重要客户", "跟进销售线索", "续约提醒", "支持工单跟进", "投诉处理"},
            {"客户A现场拜访", "客户B产品演示", "客户C需求调研", "客户D合同谈判", "合作伙伴会面"},
            {"团队建设活动", "生日庆祝", "公司年会", "部门聚餐", "户外拓展"},
            {"新产品培训", "销售技巧培训", "客户服务培训", "系统使用培训", "领导力培训"}
        };
        
        // 生成30天的随机事件
        for (int i = 1; i <= 30; i++) {
            // 每天1-3个事件
            int eventCount = 1 + random.nextInt(3);
            
            for (int j = 0; j < eventCount; j++) {
                Map<String, Object> event = new HashMap<>();
                
                event.put("id", (i * 10) + j);
                event.put("date", "2023-07-" + (i < 10 ? "0" + i : i));
                
                // 随机选择事件类型
                int typeIndex = random.nextInt(eventTypes.length);
                event.put("type", eventTypes[typeIndex]);
                
                // 根据类型选择具体内容
                event.put("title", eventContents[typeIndex][random.nextInt(eventContents[typeIndex].length)]);
                
                // 随机时间
                int hour = 8 + random.nextInt(10);
                int minute = random.nextInt(4) * 15;
                event.put("time", (hour < 10 ? "0" + hour : hour) + ":" + (minute == 0 ? "00" : minute));
                
                // 随机状态
                String[] statuses = {"upcoming", "in_progress", "completed", "canceled"};
                event.put("status", statuses[random.nextInt(statuses.length)]);
                
                // 随机添加参与者
                if (random.nextBoolean()) {
                    List<String> participants = new ArrayList<>();
                    int participantCount = 1 + random.nextInt(5);
                    String[] names = {"张三", "李四", "王五", "赵六", "钱七", "孙八", "周九"};
                    
                    for (int k = 0; k < participantCount; k++) {
                        participants.add(names[random.nextInt(names.length)]);
                    }
                    
                    event.put("participants", participants);
                }
                
                events.add(event);
            }
        }
        
        return Result.success(events);
    }
    
    /**
     * 获取通知消息
     */
    @GetMapping("/notifications")
    public Result<Map<String, Object>> getNotifications() {
        Map<String, Object> response = new HashMap<>();
        List<Map<String, Object>> notifications = new ArrayList<>();
        
        // 模拟通知数据
        String[][] notificationData = {
            {"system", "系统维护通知", "系统将于今晚22:00-23:00进行例行维护，请提前保存工作。", "3小时前"},
            {"customer", "新客户注册", "新客户「字节跳动」已完成注册，请及时跟进。", "5小时前"},
            {"sales", "销售目标提醒", "您的团队已完成本月销售目标的85%，距离月底还有5天。", "1天前"},
            {"task", "任务到期提醒", "您的任务「完成二季度销售报告」将在明天到期。", "1天前"},
            {"service", "紧急工单", "客户「华为技术」提交的工单#45678被标记为紧急，请尽快处理。", "2天前"},
            {"system", "账户安全提醒", "您的账户于昨天在新设备上登录，如非本人操作请立即修改密码。", "2天前"},
            {"customer", "客户投诉", "客户「小米科技」对最近的服务体验提出投诉，请查看详情。", "3天前"}
        };
        
        for (int i = 0; i < notificationData.length; i++) {
            Map<String, Object> notification = new HashMap<>();
            notification.put("id", i + 1);
            notification.put("type", notificationData[i][0]);
            notification.put("title", notificationData[i][1]);
            notification.put("content", notificationData[i][2]);
            notification.put("time", notificationData[i][3]);
            notification.put("read", i > 2); // 前三条未读
            
            notifications.add(notification);
        }
        
        response.put("notifications", notifications);
        response.put("unreadCount", 3);
        
        return Result.success(response);
    }
    
    /**
     * 标记通知为已读
     */
    @PostMapping("/notifications/read")
    public Result<Boolean> markNotificationsRead(@RequestBody Map<String, Object> params) {
        // 此处应调用服务层标记通知已读
        
        // 模拟返回成功
        return Result.success(true);
    }
} 